<?php

namespace App\Admin\Controllers;


use App\Models\Notice;
use App\Models\User;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;


class NoticeController extends Controller
{
    use ModelForm;
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('通知消息');
            $content->description('用于不便使用模板消息发送的通知');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('通知消息');
            $content->description('用于不便使用模板消息发送的通知');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('通知消息');
            $content->description('用于不便使用模板消息发送的通知');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Notice::class, function (Grid $grid) {
            $grid->id("ID")->sortable();
            $grid->user_id('用户id');
            $grid->title('标题');
            $grid->content('内容');
            $grid->url('链接');
            $grid->readed('是否读取')->display(function ($data){
                return $data?'是':'否';
            });

            $grid->created_at('创建时间');
            $grid->updated_at('更新时间');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Notice::class, function (Form $form) {

            $form->number('user_id','用户id');
            $form->text('title','标题');
            $form->text('content','内容');
            $form->text('url','链接')->default(0);
            //检查此用户是否存在
            $form->saving(function ($form) {
                $user=User::find($form->user_id);
                if(!$user){
                    $error = new MessageBag([
                        'title'   => '错误提示',
                        'message' => '消息用户不存在！',
                    ]);

                    return back()->with(compact('error'));
                }
            });
        });
    }


}
